import fs from "node:fs"
import { fileURLToPath } from "node:url"
import path from "node:path"
import { spawn } from "node:child_process" //开启子进程
import ora from "ora"
import download from "download-git-repo"
import { program } from "commander"
import ejs from "ejs"

// 其他options
export const helpOptions = () => {
  // 解析版本--version    -v --version为起别名，让-v查看版本号生效
  const file = fs.readFileSync("./package.json")
  program.version(JSON.parse(file).version)

  // 增加其他的options
  program.option("-g --gk", "a gk cli program~")
  program.option(
    "-d --dest <dest> ",
    "a destination folder, 例如：-d src/components"
  )

  program.on("--help", () => {
    console.log("")
    console.log("others:")
    console.log("xxxxxx")
  })
}

// 检查路径
export const checkPath = (path) => {
  return fs.existsSync(path)
}

// 下载模板
const sipnner = ora("下载中...")
export const downloadTemp = (isTs, name) => {
  return new Promise((resolve, reject) => {
    sipnner.start()
    let branch = isTs ? "ts" : "js"
    download(
      `direct:https://gitee.com/comtkun/vue-template.git#${branch}`,
      name,
      { clone: true },
      (err) => {
        if (err) {
          sipnner.fail()
          reject(err)
        } else {
          sipnner.succeed("模板下载完成，请等待项目依赖的安装")
          resolve()
        }
      }
    )
  })
}

// 执行npm install 和 npm run dev的函数
export const execCommand = (...args) => {
  return new Promise((resolve, reject) => {
    const childProcess = spawn(...args)

    childProcess.stdout.pipe(process.stdout)
    childProcess.stderr.pipe(process.stderr)

    // 监听子进程结束
    childProcess.on("close", () => {
      resolve()
    })
  })
}

// 编译ejs模板
export const compileEjs = (template, name) => {
  return new Promise((resolve, reject) => {
    // 拿到模板路径
    const tempPath = `./template/${template}`
    const __filename = fileURLToPath(import.meta.url)
    const __dirname = path.dirname(__filename)
    const absolutePath = path.resolve(__dirname, tempPath)

    // 开始编译
    ejs.renderFile(absolutePath, { name }, (err, result) => {
      if (err) {
        console.log("模板编译失败", err)
        reject(err)
        return
      }
      resolve(result)
    })
  })
}
